import React, { useState, useEffect } from 'react';
import { Button, Table, Input, Space, Select, Modal, Form, message, DatePicker } from 'antd';
import styles from './index.less';
import { getProduce, getProducers, distributionProduce, getPlanner, outMaterialRequire, inProduceRequire } from '@/api/services';
import EditProduceModal from './components/EditProduceModal';

const ProduceMangement: React.FC = () => {
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [data, setData] = useState([]);
    const [page, setPage] = useState<number>(1);
    const [total, setTotal] = useState(0);
    const [producers, setProducers] = useState<any>([]);//车间生产员
    const [planners, setPlanners] = useState<any>([]);//生产计划员
    const [modalOpen, setModalOpen] = useState<boolean>(false);
    const [customerId, setCustomerId] = useState<any>('');
    const [plannerId, setPlannerId] = useState<any>('');
    const [producerId, setProducerId] = useState<any>('');
    const [directorId, setDirectorId] = useState<any>('');
    const [editId, setEditId] = useState<any>('');

    const getProduceList = () => {
        getProduce({
            page: page,
            size: 5,
            plannerId: plannerId ? plannerId : '',
            producerId: producerId ? producerId : ''
        }).then((res: any) => {
            if (res.status == 200) {
                console.log(res);
                setData(res.results);
                setTotal(res.length);
            }

        });
    }

    useEffect(() => {
        getProduceList();
    }, [page, producerId, plannerId]);

    //委派生产订单
    const handleSelectChange = (id: any, value: any) => {
        distributionProduce({
            productId: id,
            producerId: value
        }).then((res: any) => {
            if (res.status == 200) {
                console.log(res);
                message.success('委派成功');
                getProduceList();
            }

        })
    }

    const handleChange = (pagination: any, filters: any, sorter: any) => {
        console.log(filters);
        const plannerName = filters.plannerName ? filters.plannerName[0] : '';
        setPlannerId(plannerName);
        const directorName = filters.producerName ? filters.producerName[0] : '';
        setProducerId(directorName);
    };

    const hasSelected = selectedRowKeys.length > 0;

    //车间生产员
    useEffect(() => {
        getProducers().then((res: any) => {
            if (res.status == 200) {
                console.log(res);
                const options = res.results.map((user: any) => ({
                    value: user.user_id,
                    label: user.user_name,
                }));
                setProducers(options);
            }

        })
    }, [])

    //生产计划员
    useEffect(() => {
        getPlanner().then((res: any) => {
            if (res.status == 200) {
                console.log(res);
                const options = res.results.map((user: any) => ({
                    value: user.user_id,
                    label: user.user_name,
                }));
                setPlanners(options);
            }

        })
    }, [])
    // const formatDetail = (str: string) => {

    // }


    const handleEditCancel = () => {
        setModalOpen(false);
    }

    //原料提库申请
    const outWareHouse = (id: any, detail: any) => {
        outMaterialRequire({
            productId: id,
            mtdetail: detail
        }).then((res: any) => {
            if (res.status == 200) {
                message.success(res.msg);
                getProduceList();
            }
        })
    }

    //产品入库申请
    const inWareHouse = (id: any, detail: any) => {
        inProduceRequire({
            productId: id,
            ocdetail: detail
        }).then((res: any) => {
            if (res.status == 200) {
                message.success(res.msg);
                getProduceList();
            }
        })
    }

    const paginationConfig = {
        total: total,
        onChange: (page: number, pageSize?: number) => {
            setPage(page);
        },
        showTotal: (total: number, range: [number, number]) => `共 ${total} 条数据`,
    }
    const formatDetail = (data: any) => {
        var dataArray = data.split("||");
        var result = "";

        // 遍历数组中的每一对数据
        for (var i = 0; i < dataArray.length; i += 2) {
            // 获取物品名称和数量
            var item = dataArray[i]?.trim();
            var quantity = dataArray[i + 1]?.trim();

            // 格式化为键值对的形式，并添加到结果中
            result += item + "：" + quantity;

            // 如果不是最后一对数据，添加逗号分隔符
            if (i < dataArray.length - 2) {
                result += ", ";
            }
        }

        return result;
    }


    const columns = [
        {
            title: '原料明细',
            dataIndex: 'product_mtdetail',
            width: 150,
            render: (_: any, record: any) => (
                <div>
                    <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
                        {record.product_mtdetail && formatDetail(record.product_mtdetail).split(',').map((item: any, index: number) => (
                            <span key={index}>{item}</span>
                        ))}
                    </Space>
                </div>
            )
        },
        {
            title: '产物明细',
            dataIndex: 'product_ocdetail',
            width: 150,
            render: (_: any, record: any) => (
                <div>
                    <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
                        {record.product_ocdetail && formatDetail(record.product_ocdetail).split(',').map((item: any, index: number) => (
                            <span key={index}>{item}</span>
                        ))}
                    </Space>
                </div>
            )
        },
        {
            title: '生产订单提交时间',
            dataIndex: 'product_posttime',
        },
        {
            title: '生产截止时间',
            dataIndex: 'product_deadline',
        },
        {
            title: '订单截止时间',
            dataIndex: 'product_ordead'
        },
        {
            title: '订单状态',
            dataIndex: 'product_type',
        },
        {
            title: '生产计划员',
            dataIndex: 'plannerName',
            filters: planners.map((user: any) => ({
                value: user.value,
                text: user.label
            })),
        },
        {
            title: '车间生产员',
            dataIndex: 'producerName',
            filters: producers.map((user: any) => ({
                value: user.value,
                text: user.label
            })),
            render: (_: any, record: any) => (
                <Select
                    style={{ width: 120 }}
                    onChange={(value) => handleSelectChange(record.product_id, value)}
                    value={record.producerName}
                    options={producers}
                />
            )
        },
        {
            title: 'Action',
            dataIndex: '',
            key: 'x',
            render: (_: any, record: any) =>
                <Space size="middle">
                    <a
                        onClick={() => {
                            setModalOpen(true)
                            console.log(record);
                            setEditId(record.product_id);
                        }}
                    >编辑</a>
                    {
                        record.product_mtdetail !== null ?
                            <a
                                onClick={() => outWareHouse(record.product_id, record.product_mtdetail)}
                            >原料提库</a> :
                            <a
                                onClick={() => message.info('请等待生产计划员编辑')}
                            >原料提库</a>
                    }
                    {
                        record.product_type == '生产中' ?
                            <a
                                onClick={() => inWareHouse(record.product_id, record.product_ocdetail)}
                            >产品入库</a> :
                            <a
                                onClick={() => {
                                    if(record.product_type == '入库中' || record.product_type == '已完成'){
                                        message.info('已提交产品入库申请')
                                    } else {
                                        message.info('未生产完成')
                                    }
                                }}
                            >产品入库</a>
                    }

                </Space>
        },
    ];

    return (
        <div className={styles.orderContainer}>

            <div className={styles.header}>

            </div>
            <Table 
                onChange={handleChange}
                pagination={paginationConfig}
                columns={columns} dataSource={data} />
            {modalOpen && <EditProduceModal onCancel={handleEditCancel} editId={editId} getProduceList={getProduceList} />}
        </div>

    );
};

export default ProduceMangement;